package com.guyan.controller;

import com.github.pagehelper.PageInfo;
import com.guyan.entity.User;
import com.guyan.form.UserForm;
import com.guyan.service.UserService;
import com.guyan.vo.LayuiVo;
import com.guyan.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * ClassName： UserController
 * Date： 2021/6/11 13:50
 *
 * @author 孤焰
 * @version 1.0
 **/

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResultVo login(String username, String password, HttpSession session) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ResultVo.error(4000, "用户名或密码不能为空");
        }

        ResultVo resultVo = userService.login(username, password);
        if (resultVo.getCode() == 200) {
            session.setAttribute("user", resultVo.getData());
        }

        resultVo.setData(null);
        return resultVo;
    }

    @GetMapping("/userList")
    public LayuiVo userList(@RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer limit) {
        PageInfo pageInfo = userService.userList(page, limit);

        return LayuiVo.success(pageInfo.getTotal(), pageInfo.getList());
    }

    @PostMapping("/addUser")
    public ResultVo addUser(@RequestBody @Valid UserForm userForm, BindingResult bindingResult) {
        if (bindingResult.getErrorCount() > 0) {
            return ResultVo.error(7000, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        User user = new User();
        BeanUtils.copyProperties(userForm, user);

        return userService.addUser(user);
    }

    @PostMapping("/updateUserById")
    public ResultVo updateUserById(@RequestBody User user) {
        return userService.updateUserById(user);
    }

    @PostMapping("/batchDelUser")
    public ResultVo batchDelUser(@RequestBody Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return ResultVo.error(5001, "未选择要删除的产品");
        }

        return userService.batchDelUser(ids);
    }
}
